package com.spider.admin.scaffold.common.handler;


import com.spider.admin.scaffold.common.Result;
import com.spider.admin.scaffold.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

/**
 * 全局异常处理类
 *
 * @author xiong.bo
 * @version 1.0
 * @date 2025/3/22 10:54 上午
 */

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


  @ExceptionHandler(BadCredentialsException.class)
  public ResponseEntity<?> handleAuthenticationException(BadCredentialsException ex,
      WebRequest request) {
    Result result = Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
    log.error("BadCredentialsException：{}", ex.getMessage());
    return new ResponseEntity<>(result, HttpStatus.UNAUTHORIZED);
  }

  @ExceptionHandler(AuthenticationException.class)
  public ResponseEntity<?> handleAuthenticationException(AuthenticationException ex,
      WebRequest request) {
    Result<Void> result = Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
    log.error("AuthenticationException：{}", ex.getMessage());
    return new ResponseEntity<>(result, HttpStatus.UNAUTHORIZED);
  }

  @ExceptionHandler(InvalidTokenException.class)
  public ResponseEntity<?> handleAuthenticationException(InvalidTokenException ex,
      WebRequest request) {
    Result<Void> result = Result.error(ex.getHttpErrorCode(), ex.getMessage());
    log.error("InvalidTokenException：{}", ex.getMessage());
    return new ResponseEntity<>(result, HttpStatus.UNAUTHORIZED);
  }

  @ExceptionHandler(BusinessException.class)
  public ResponseEntity<?> handleGlobalException(BusinessException ex, WebRequest request) {
    Result<Void> result = Result.error(ex.getCode(), ex.getMessage());
    log.error("BusinessException：{}", ex.getMessage());
    return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
  }

  @ExceptionHandler(Exception.class)
  public ResponseEntity<?> handleGlobalException(Exception ex, WebRequest request) {
    Result<Void> result = Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
    log.error("系统异常", ex);
    return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
  }

}